package com.yonyou.pmclouds.workquality.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.bp.processor.AuditInfoUpdateProcessor;
import com.yonyou.pmclouds.basecom.bp.template.SingleUpdateBpTemplate;
import com.yonyou.pmclouds.basecom.consts.EnableStatusConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.workquality.entity.WorkqualityDetailVO;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.mapper.WorkqualityDetailMapper;
import com.yonyou.pmclouds.workquality.mapper.WorkqualityMapper;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkQuaDetailMaintain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = WorkQuaDetailMaintain.class)
public class WorkQuaDetailMaintainImpl implements WorkQuaDetailMaintain {

    @Autowired
    private WorkqualityMapper mapper;

    @Autowired
    private WorkqualityDetailMapper detailMapper;

    @Override
    public WorkqualityDetailVO enable(WorkqualityDetailVO detailVO) throws BusinessException {
        if (StringUtils.isNotEmpty(detailVO.getPkWorkquality()) && !isParentEnable(detailVO))
            throw new BusinessException("所选数据的检查标准为停用状态，请先启用检查标准。");
        // 启用
        return updateEnableStatus(detailVO, EnableStatusConst.ENABLE);
    }

    @Override
    public WorkqualityDetailVO disable(WorkqualityDetailVO detailVO) throws BusinessException {
        if (StringUtils.isNotEmpty(detailVO.getPkWorkquality()) && !isParentEnable(detailVO))
            throw new BusinessException("所选数据的检查标准为停用状态，请先启用检查标准。");
        // 停用
        return updateEnableStatus(detailVO, EnableStatusConst.DISABLE);
    }

    /**
     * 更新VO启用状态
     *
     * @param detailVO
     * @param status
     * @throws BusinessException
     */
    private WorkqualityDetailVO updateEnableStatus(WorkqualityDetailVO detailVO, byte status) throws BusinessException {
        SingleUpdateBpTemplate<WorkqualityDetailVO> bp = new SingleUpdateBpTemplate(detailMapper, new String[]{EnableStatusConst.ENABLE_STATUS});
        detailVO.setEnableStatus(status);
        bp.addBeforeProcessor(new AuditInfoUpdateProcessor<WorkqualityDetailVO>());

        return bp.update(detailVO);
    }

    /**
     * 判断上级是否启用
     *
     * @param detailVO
     * @return
     */
    private boolean isParentEnable(WorkqualityDetailVO detailVO) {
        WorkqualityVO parentVO = mapper.getById(detailVO.getPkWorkquality());
        if (parentVO != null && parentVO.getEnableStatus() == EnableStatusConst.ENABLE)
            return true;

        return false;
    }
}
